﻿/**************************************************************************
创建时间:	2020/5/15 
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述：
记	录：
***************************************************************************/
using System.Collections.Generic;
using System.Data;
using ZhCun.DbCore.Cores;
using ZhCun.DBModel;
using ZhCun.Utils;
using ZhCun.Utils.Helpers;
using ZhCun.Win.DB;

namespace ZhCun.Win.MenuRole
{
    class MenuRoleBLL : BLLBase
    {
        #region 角色维护

        protected ApiResult<string> RoleVerifyModel(Sys_Role model, bool isAdd)
        {
            if (model.RoleName.IsEmpty())
            {
                return ApiResult.RetErr(Sys_Role.CNRoleName, "角色名称不能为空");
            }
            if (DB.QueryExist<Sys_Role>(s => s.RoleName == model.RoleName && s.Id != model.Id))
            {
                return ApiResult.RetErr(Sys_Role.CNRoleName, "角色名称重复");
            }
            return ApiResult.RetOK("", "保存成功");
        }
        /// <summary>
        /// 新增保存
        /// </summary>
        public virtual ApiResult<string> RoleAdd(Sys_Role model)
        {
            var ret = RoleVerifyModel(model, true);
            if (ret)
            {
                DB.Insert(model);
            }
            return ret;
        }
        /// <summary>
        /// 编辑保存
        /// </summary>
        public virtual ApiResult<string> RoleEdit(Sys_Role model)
        {
            var ret = RoleVerifyModel(model, false);
            if (ret)
            {
                DB.Update(model);
            }
            return ret;
        }
        /// <summary>
        /// 删除
        /// </summary>
        public ApiResult RoleDel(Sys_Role model)
        {
            if (DB.QueryExist<Sys_Role_Menu>(s => s.RoleId == model.Id))
            {
                return ApiResult.RetErr("菜单中已经使用，请先移除角色中的菜单");
            }
            DB.Delete<Sys_Role>(s => s.Id == model.Id);
            return ApiResult.RetOK("删除成功");
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        public DataTable RoleGetData()
        {
            var query = DB.CreateQuery<Sys_Role>();
            var ret = DB.Query<Sys_Role>(query);
            var dt = ret.ToDataTable();
            return dt;
        }

        #endregion

        #region 菜单树

        /// <summary>
        /// 菜单分类列表（非菜单的树形结构）
        /// </summary>
        public List<Sys_Role_Menu> TreeGetData(string roleId)
        {
            var query = DB.CreateQuery<Sys_Role_Menu>();
            query.WhereAnd(s => s.RoleId == roleId);
            query.OrderBy(s => s.OrderNo);
            var r = DB.Query<Sys_Role_Menu>(query).ToList(true);
            return r;
        }

        ApiResult<string> VerifyTreeModel(Sys_Role_Menu m, bool isAdd)
        {
            if (m.MenuCaption.IsEmpty())
            {
                return ApiResult.RetErr(nameof(m.MenuCaption), "分类名称不能为空");
            }

            if (DB.QueryExist<Sys_Role_Menu>(s =>
                s.RoleId == m.RoleId && s.PId == m.PId && s.Id != m.Id && m.MenuCaption == m.MenuCaption))
            {
                return ApiResult.RetErr(nameof(m.MenuCaption), "分类名称已经存在");
            }
            return ApiResult.RetOK(string.Empty, "保存成功！");
        }

        public ApiResult<string> TreeAdd(Sys_Role_Menu m)
        {
            var ret = VerifyTreeModel(m, true);
            if (!ret)
            {
                return ret;
            }
            if (DB.QueryExist<Sys_Menu>(s => s.PId == m.PId && s.MenuCaption == m.MenuCaption))
            {
                return ApiResult.RetErr(nameof(m.MenuCaption), "当前节点下菜单名称重复");
            }
            //if (DB.QueryExist<Sys_Menu>(s => s.PId == m.PId && s.IsMenu == true))
            //{
            //    return ApiResult.RetErr(string.Empty, "当前菜单分类已经分配菜单，不允许增加子级分类");
            //}
            var r = DB.Insert(m);
            if (r.RowCount == 1)
            {
                return ApiResult.RetOK(string.Empty, "增加成功");
            }
            return ret;
        }

        public ApiResult<string> TreeEdit(Sys_Role_Menu m)
        {
            var ret = VerifyTreeModel(m, false);
            if (!ret)
            {
                return ret;
            }
            var r = DB.Update(m);
            if (r.RowCount == 1)
            {
                return ApiResult.RetOK(string.Empty, "更新成功");
            }
            return ret;
        }

        public ApiResult TreeChangeParentId(Sys_Role_Menu m, string pId)
        {
            ExecResult r;
            if (pId == m.PId)
            {
                r = DB.UpdateByExpr<Sys_Role_Menu>(
                    s => s.PId == m.PId && s.OrderNo >= m.OrderNo,
                    "OrderNo = OrderNo + 1");
            }
            else
            {
                m.PId = pId;
                r = DB.Update(m);
            }
            if (r.RowCount == 1)
            {
                return ApiResult.RetOK("修改成功");
            }
            return ApiResult.RetOK("修改失败");
        }

        public ApiResult TreeDel(Sys_Role_Menu menu)
        {
            if (DB.QueryExist<Sys_Role_Menu>(s => s.PId == menu.Id))
            {
                return ApiResult.RetErr("请先移除所子级节点及菜单");
            }
            var ret = DB.Delete<Sys_Role_Menu>(s => s.Id == menu.Id);
            if (ret.RowCount == 1)
            {
                return ApiResult.RetOK("删除成功");
            }
            return ApiResult.RetErr("删除失败");
        }

        #endregion

        #region 角色菜单

        public List<Sys_Menu> GetMenuTree()
        {
            var query = DB.CreateQuery<Sys_Menu>();
            query.OrderBy(s => s.OrderNo);
            var menuList = DB.Query<Sys_Menu>(query).ToList(true);
            return menuList;
        }

        ApiResult<string> VerifyMenuModel(Sys_Role_Menu t, bool isAdd)
        {
            if (t.MenuCaption.IsEmpty())
            {
                return ApiResult.RetErr(nameof(t.MenuCaption), "菜单标题不能为空");
            }
            if (t.MenuName.IsEmpty() || t.MenuId.IsEmpty())
            {
                return ApiResult.RetErr(nameof(t.MenuName), "菜单名称不能为空");
            }
            if (DB.QueryExist<Sys_Role_Menu>(s => s.RoleId == t.RoleId && s.PId == t.PId && s.MenuName == t.MenuName && s.Id != t.Id))
            {
                return ApiResult.RetErr(nameof(t.MenuName), "菜单已经存在当前角色下");
            }


            return ApiResult.RetOK(string.Empty, "保存成功");
        }

        public ApiResult<string> AddRoleMenu(Sys_Role_Menu model)
        {
            var ret = VerifyMenuModel(model, true);
            if (!ret)
            {
                return ret;
            }
            model.ClearChangedState(Sys_Menu.CNId);
            model.IsMenu = true;
            DB.Insert(model);
            return ApiResult.RetOK(string.Empty, "增加菜单成功");
        }

        public ApiResult<string> EditRoleMenu(Sys_Role_Menu model)
        {
            var ret = VerifyMenuModel(model, true);
            if (!ret)
            {
                return ret;
            }
            DB.Update(model);
            return ApiResult.RetOK(string.Empty, "修改菜单成功");
        }

        public ApiResult DelRoleMenu(Sys_Role_Menu model)
        {
            var ret = DB.Delete<Sys_Role_Menu>(s => s.Id == model.Id);
            if (ret.RowCount == 1)
            {
                return ApiResult.RetOK("删除成功");
            }
            else
            {
                return ApiResult.RetOK("删除失败，记录不存在！");
            }
        }

        /// <summary>
        /// 根据父级Id获取所有子菜单
        /// </summary>
        public DataTable GetRoleMenus(string roleId, string pId, string searchVal, bool isToorBar = false)
        {
            var query = DB.CreateQuery<Sys_Role_Menu>();
            query.WhereAnd(s => s.RoleId == roleId);
            if (isToorBar)
            {
                query.WhereAnd(s => s.ToolBarVisible == true);
            }
            else
            {
                query.WhereAnd(s => s.PId == pId);
            }
            if (!searchVal.IsEmpty())
            {
                string likeStr = $"%{searchVal}%";
                query.WhereAnd(s =>
                    s.WEx_Like(s.MenuCaption, likeStr) ||
                    s.WEx_Like(s.MenuName, likeStr));
            }
            if (isToorBar)
            {
                query.OrderBy(s => s.ToolBarOrderNo);
            }
            else
            {
                query.OrderBy(s => s.OrderNo);
            }
            var dt = DB.Query<Sys_Role_Menu>(query).ToDataTable();
            return dt;
        }

        #endregion

        public List<Sys_Role_Menu> GetMenuByRole(string roleId)
        {
            var query = DB.CreateQuery<Sys_Role_Menu>();
            query.WhereAnd(s => s.RoleId == roleId);
            query.OrderBy(s => s.PId).OrderBy(s => s.OrderNo);
            var r = DB.Query<Sys_Role_Menu>(query);
            return r.ToList(true);
        }
    }
}